/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package doc2db;

import doc2db.fileWorker.FileBeginer;
import doc2db.fileWorker.FileIO;
import doc2db.fileWorker.FileWorker;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Toolkit;
import java.util.Date;
import java.util.Properties;

/**
 *
 * @author yuriy
 */
public class UserProp {
    /** Дата создания пользователя */
    public static String datacreating = "" + new Date();//.getDate();
    /**
     * <p>Системный псевдоним</p>
     */
    public static String user = "__NULL";
    /**
     * <p>Имя пользователя для конекта к БД</p>
     */
    public static String userInDb = "__NULL";

    /**
     * <p>Системный пароль</p>
     */
    public static String pswd = "__NULL";
    /**
     * <p>Пароль пользователя для конекта к БД</p>
     */
    public static String pswdInDb = "__NULL";
    /**
     *  <p>фонты в меню приложения</p>
     */
    public static Font menuFont = new Font (Font.MONOSPACED, Font.PLAIN, 12);
    /**
     *  <p>фонты главной панели в приложенеи</p>
     */
    public static Font paneFont = new Font (Font.MONOSPACED, Font.PLAIN, 14);
    /**
     *  <p>фонты в текстовых полях в приложенеи</p>
     */
    public static Font textFont = new Font (Font.SANS_SERIF, Font.PLAIN, 14);
    /**
     * <p>Внешний вид</p>
     */
    public static String lookAndFeel = Keey.lookAndFeel();
    /** Show button "createMyCon" in toolbar */
    public static boolean createMyCon = false;
    /** Show button "createNewCon" in toolbar */
    public static boolean createNewCon = false;
    /** Show button "closeCon" in toolbar */
    public static boolean closeCon = false;
    /** Show button "tableList" in toolbar */
    public static boolean tableList = true;
    /** Show button "createTempl" in toolbar */
    public static boolean createTempl = false;
    /** Show button "choiceTempl" in toolbar */
    public static boolean choiceTempl = false;
    /** Show button "corectTempl" in toolbar */
    public static boolean corectTempl = false;
    /** Show button "corectTemplInDb" in toolbar */
    public static boolean corectTemplInDb = false;
    /** Show button "showTable" in toolbar */
    public static boolean showTable = true;
    /** Show button "delTable" in toolbar */
    public static boolean delTable = true;
    /** Show button "insert" in toolbar */
    public static boolean insert = false;
    /** Show button "update" in toolbar */
    public static boolean update = false;
    /** Show button "createTable" in toolbar */
    public static boolean createTable = false;
    /** Show button "modetab" in toolbar */
    public static boolean modetab = false;

    /** Show button "save" in toolbar */
    public static boolean save = false;
    /** Show button "saveAs" in toolbar */
    public static boolean saveAs = false;
    /** Show button "open" in toolbar */
    public static boolean open = false;
    /** Show button "openDir" in toolbar */
    public static boolean openDir = false;

    /** Show  toolbar */
    public static boolean seeAll = true;
    /** показать запросы к БД */
    public static boolean textDBSelects = true;
    /**stdOut/stdErr*/
    public static boolean textOut = true;
    /**показать выходные данные с БД*/
    public static boolean textWeekendInformation = true;
    /**показать шаблон*/
    public static boolean textTemplete = true;
    /**показать поле ввода <i>sql</i> запросов*/
    public static boolean sqlSelectsArea = true;
    /**показать поле ввода файла и дополняющих его компонентов*/
    public static boolean fileEntryField = true;
    /**Имя базы данных для работы*/
    public static String dbName = "test";
    /**Адрес базы данных для работы*/
    public static String dbHost = "localhost";
    /** Размер главного окна */
    public static Dimension size = new Dimension(400, 470);
    /** Позиция главного окна */
    public static Dimension location = new Dimension(
            Toolkit.getDefaultToolkit().getScreenSize().width /6,
            Toolkit.getDefaultToolkit().getScreenSize().height/6);

    /** Load user data */
    public void insertData(){
        if(Keey.debug)
            System.out.println("insertData");

        String fileName = FileBeginer.resurse_users_usersFolder
                + Keey.sp + user + Keey.sp + "prop.ini";

        datacreating = FileWorker.howInit(fileName, "dataCreating");
        if(datacreating.equals("null"))
            datacreating = "ERROR:" + new Date();//.getDate();

        menuFont = insertFont(FileWorker.howInit(fileName, "fontMenu"), menuFont);
        paneFont = insertFont(FileWorker.howInit(fileName, "fontPanel"), paneFont);
        textFont = insertFont(FileWorker.howInit(fileName, "fontText"), textFont);

        size = insertDimension(FileWorker.howInit(fileName, "frameSize"), size);
        location = insertDimension(FileWorker.howInit(fileName, "frameLocation"), location);

        lookAndFeel = FileWorker.howInit(fileName, "lookAndFeel");
        if(lookAndFeel.equals("null"))
            lookAndFeel = Keey.lookAndFeel();

        createMyCon = Boolean.parseBoolean(FileWorker.howInit(fileName, "createMyCon"));
        createNewCon = Boolean.parseBoolean(FileWorker.howInit(fileName, "createNewCon"));
        closeCon = Boolean.parseBoolean(FileWorker.howInit(fileName, "closeCon"));
        tableList = Boolean.parseBoolean(FileWorker.howInit(fileName, "tableList"));
        showTable = Boolean.parseBoolean(FileWorker.howInit(fileName, "showTable"));
        delTable = Boolean.parseBoolean(FileWorker.howInit(fileName, "delTable"));
        insert = Boolean.parseBoolean(FileWorker.howInit(fileName, "insert"));
        update = Boolean.parseBoolean(FileWorker.howInit(fileName, "update"));
        modetab = Boolean.parseBoolean(FileWorker.howInit(fileName, "modetab"));
        createTable = Boolean.parseBoolean(FileWorker.howInit(fileName, "createTable"));
        seeAll = Boolean.parseBoolean(FileWorker.howInit(fileName, "seeAll"));
        createTempl = Boolean.parseBoolean(FileWorker.howInit(fileName,"createTempl"));
        choiceTempl = Boolean.parseBoolean(FileWorker.howInit(fileName,"choiceTempl"));
        corectTempl = Boolean.parseBoolean(FileWorker.howInit(fileName,"corectTemplInDb"));
        corectTemplInDb = Boolean.parseBoolean(FileWorker.howInit(fileName,"corectTemplInDb"));
        textDBSelects = Boolean.parseBoolean(FileWorker.howInit(fileName,"textDBSelects"));
        textOut = Boolean.parseBoolean(FileWorker.howInit(fileName,"textOut"));
        textWeekendInformation = Boolean.parseBoolean(FileWorker.howInit(fileName,"textWeekendInformation"));
        textTemplete = Boolean.parseBoolean(FileWorker.howInit(fileName,"textTemplete"));
        sqlSelectsArea = Boolean.parseBoolean(FileWorker.howInit(fileName,"sqlSelectsArea"));
        fileEntryField = Boolean.parseBoolean(FileWorker.howInit(fileName,"fileEntryField"));

        open = Boolean.parseBoolean(FileWorker.howInit(fileName,"open"));
        openDir = Boolean.parseBoolean(FileWorker.howInit(fileName,"openDir"));
        save = Boolean.parseBoolean(FileWorker.howInit(fileName,"save"));
        saveAs = Boolean.parseBoolean(FileWorker.howInit(fileName,"saveAs"));

        dbName = FileWorker.howInit(fileName, "dbName");
        if (dbName.equals("null")) {
            dbName = "test";
        }
        dbHost = FileWorker.howInit(fileName, "dbHost");
        if (dbHost.equals("null")) {
            dbHost = "localhost";
        }
    }

    private Font insertFont(String strFont, Font f){
        String fonts [] = strFont.split(",");
        if (fonts.length < 2) {
            return insertFont(strFont + "," + f.getStyle(), f);
        }
        if (fonts.length < 3) {
            return insertFont(strFont + "," + f.getSize(), f);
        }
        Font retF;
        try {
            retF = new Font(fonts[0].trim(), Integer.parseInt(fonts[1].trim()),
                    Integer.parseInt(fonts[2].trim()));
        } catch (Exception ex) {
            System.err.println("load user data: descript  - font" + strFont);
            return new Font(f.getName(), f.getStyle(), f.getSize());
        }
        return retF;
    }

    private Dimension insertDimension(String strDim, Dimension d){
        String dim [] = strDim.split("x");
        if (dim.length < 2) {
            return new Dimension(d);
        }
        Dimension retD;
        try{
            retD = new Dimension(Integer.parseInt(dim[0].trim()),
                                 Integer.parseInt(dim[1].trim()));
        }catch(Exception ex){
            return new Dimension(d);
        }
        return retD;
    }

    /**
     * <p>Заносим данные в файл</p>
     */
    public void writeData(Dimension size, Dimension location){
        String str2 = FileBeginer.resurse_users_usersFolder
                + Keey.sp + user + Keey.sp + "prop.ini";
        FileIO.createFile("", str2);
        FileWorker.addNewProperty(str2, "dataCreating", datacreating);
        FileWorker.addNewProperty(str2, "name", user);
        FileWorker.addNewProperty(str2, "pswd", Keey.decodStr(pswd));
        FileWorker.addNewProperty(str2, "fontPanel", 
                paneFont.getName()+","+paneFont.getStyle()+","+paneFont.getSize());
        FileWorker.addNewProperty(str2, "fontMenu",
                menuFont.getName()+","+menuFont.getStyle()+","+menuFont.getSize());
        FileWorker.addNewProperty(str2, "fontText",
                textFont.getName()+","+textFont.getStyle()+","+textFont.getSize());
        FileWorker.addNewProperty(str2, "frameSize",
                size.width + "x" + size.height);
        FileWorker.addNewProperty(str2, "frameLocation",
                location.width + "x" + location.height);
        FileWorker.addNewProperty(str2, "lookAndFeel", lookAndFeel);
        FileWorker.addNewProperty(str2, "createMyCon", ""+createMyCon);
        FileWorker.addNewProperty(str2, "createNewCon", ""+createNewCon);
        FileWorker.addNewProperty(str2, "closeCon", ""+closeCon);
        FileWorker.addNewProperty(str2, "createTempl", "" + createTempl);
        FileWorker.addNewProperty(str2, "choiceTempl", "" + choiceTempl);
        FileWorker.addNewProperty(str2, "corectTempl", "" + corectTempl);
        FileWorker.addNewProperty(str2, "corectTemplInDb", "" + corectTemplInDb);
        FileWorker.addNewProperty(str2, "tableList", ""+tableList);
        FileWorker.addNewProperty(str2, "showTable", ""+showTable);
        FileWorker.addNewProperty(str2, "delTable", ""+delTable);
        FileWorker.addNewProperty(str2, "insert", ""+insert);
        FileWorker.addNewProperty(str2, "modetab", ""+modetab);
        FileWorker.addNewProperty(str2, "update", ""+update);
        FileWorker.addNewProperty(str2, "createTable", ""+createTable);
        FileWorker.addNewProperty(str2, "seeAll", ""+seeAll);
        FileWorker.addNewProperty(str2, "textDBSelects",""+textDBSelects);
        FileWorker.addNewProperty(str2, "textOut",""+textOut);
        FileWorker.addNewProperty(str2, "textWeekendInformation",""+textWeekendInformation);
        FileWorker.addNewProperty(str2, "textTemplete",""+textTemplete);
        FileWorker.addNewProperty(str2, "sqlSelectsArea",""+sqlSelectsArea);
        FileWorker.addNewProperty(str2, "fileEntryField",""+fileEntryField);
        FileWorker.addNewProperty(str2, "save", "" + save);
        FileWorker.addNewProperty(str2, "saveAs", "" + saveAs);
        FileWorker.addNewProperty(str2, "open", "" + open);
        FileWorker.addNewProperty(str2, "openDir", "" + openDir);
        FileWorker.addNewProperty(str2, "dbName", dbName);
        FileWorker.addNewProperty(str2, "dbHost", dbHost);
    }

    public Properties getUserProp(){
        Properties p = new Properties();
        p.setProperty("user", userInDb);
        p.setProperty("password", pswdInDb);
        return p;
    }

    public String getURL(){
        String port = "5432";
        StringBuffer url = new StringBuffer();
        url.append("jdbc:postgresql://").append(dbHost).append(":")
                .append(port).append("/").append(dbName);
        
        return url.toString();
    }

    /**
     * <p>Находит параметры пользователя для базы с описанием шаблона.</p>
     * <p>"dbName" - имя БД</p>
     * <p>"dbHost" - адрес БД</p>
     * <p>"user" - имя пользователя в БД</p>
     * <p>"dbTableName" - название таблиц с шаблонами</p>
     * <p>"isAllProp" - все ли, выше перечисленные параметры
     * есть (true/false)</p>
     * @return Properties
     */
    public Properties getPropToTemplatesDb(){
        Properties p = new Properties();
        
        String str = FileBeginer.resurse_resurseFolder + Keey.sp + FileBeginer.sqlSelects;
        String prop[][] = FileWorker.getProprtyList(str);
        
        p.setProperty("isAllProp", "" + this.isAllProp(prop, p));

        return p;
    }

    private boolean isAllProp(String[][] str, Properties pr) {
        boolean tdbName = false;
        boolean tdbHost = false;
        boolean tdbUser = false;
        boolean tdbTableName = false;
        for (int i = 0; i < str.length; i++) {
            if (str[i][0].equals("templatesDbName")) {
                tdbName = true;
                pr.setProperty("dbName", str[i][1]);
            }
            if (str[i][0].equals("templatesDbHost")) {
                tdbHost = true;
                pr.setProperty("dbHost", str[i][1]);
            }
            if (str[i][0].equals("templatesDbUser")) {
                tdbUser = true;
                pr.setProperty("user", str[i][1]);
            }
            if (str[i][0].equals("templatesDbTableName")) {
                tdbTableName = true;
                pr.setProperty("dbTableName", str[i][1]);
            }
        }

        return tdbName && tdbHost && tdbUser && tdbTableName;
    }

}
